var consoleUtil = require('../utils/consoleUtils');
var constantUtil = require('../utils/constant.js');
var stringUtils = require('../utils/stringUtils.js');
var sha256 = require('../utils/sha256.js');
/**
 * url:请求的url
 * params:请求参数
 * message:loading提示信息
 * success:成功的回调
 * fail:失败的回调
 */

//post请求
function postRequest(url, params, success, fail) {
	this.postRequestLoading(url, params, '', success, fail);
}

//根据判断message 是否显示loading
function postRequestLoading(url, params, message, success, fail) {
	if (message != '') {
		uni.showLoading({
			mask: true
			// title: message,
		});
	}

	consoleUtil.log(url);
	consoleUtil.log(params);
	const postRequestTask = uni.request({
		url: url,
		data: params,
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		},
		method: 'POST',
		success: function(res) {
			if (message != '') {
				uni.hideLoading();
			}
			if (res.statusCode == 200) {
				consoleUtil.log(res.data);
				success(res.data);
			} else {
				fail(res);
			}
		},
		fail: function(res) {
			consoleUtil.log(res);
			if (message != '') {
				uni.hideLoading();
			}
			fail(res);
		}
	});
}
//根据判断message 是否显示loading
function postRequestLoading2(url, params, message, success, fail) {
	if (message != '') {
		uni.showLoading({
			mask: true
			// title: message,
		});
	}

	consoleUtil.log(url);
	consoleUtil.log(params);
	const postRequestTask = uni.request({
		url: url,
		data: params,
		// header: {
		//     'content-type': 'multipart/form-data'
		// },
		method: 'POST',
		success: function(res) {
			if (message != '') {
				uni.hideLoading();
			}
			if (res.statusCode == 200) {
				consoleUtil.log(res.data);
				if (res.data.code == 999) {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					});
					uni.navigateTo({
						url: '/pages/login/login?fromType=999'
					})

				}
				success(res.data);
			} else {
				fail(res);
			}
		},
		fail: function(res) {
			consoleUtil.log(res);
			if (message != '') {
				uni.hideLoading();
			}
			fail(res);
		}
	});
}
//无需校验的接口：注册、获得token
function postRequestLG(url, params, message, success, fail) {
	if (message != '') {
		uni.showLoading({
			mask: true
			// title: message,
		});
	}

	consoleUtil.log(url);
	consoleUtil.log(params);
	const postRequestTask = uni.request({
		url: url,
		data: params,
		//之前用的
		// header: {
		//     'content-type': 'application/x-www-form-urlencoded'
		//   },

		// header: {
		// 'content-type': 'multipart/form-data'
		// },
		method: 'POST',
		success: function(res) {
			if (message != '') {
				uni.hideLoading();
			}
			if (res.statusCode == 200) {
				consoleUtil.log(res.data);
				success(res.data);
			} else {
				fail(res.data);
			}
		},
		fail: function(res) {
			consoleUtil.log(res);
			if (message != '') {
				uni.hideLoading();
			}
			fail(res);
		}
	});
}
//此接口只获得token
function getToken(userId, message) {
	if (message != '') {
		uni.showLoading({
			mask: true
			// title: message,
		});
	}

	let url = constantUtil.getAccessToken;
	let params = {
		customId: constantUtil.customId,
		userId: userId,
		timestamp: stringUtils.getTimestamp(),
		appKey: constantUtil.appKey,
		appId: constantUtil.appId,
		sign: sha256.hex_sha256(constantUtil.customId + '\n' + constantUtil.appKey + '\n' + constantUtil.appId +
			'\n' + constantUtil.secretKey + '\n' + userId)
	};
	consoleUtil.log(url);
	consoleUtil.log(params);
	const postRequestTask = uni.request({
		url: url,
		data: params,
		method: 'POST',
		success: function(res) {
			if (message != '') {
				uni.hideLoading();
			}
			if (res.statusCode == 200) {
				consoleUtil.log(res.data);
				uni.setStorageSync(constantUtil.tokenData, res.data.data);
				uni.setStorageSync(constantUtil.token, res.data.data.token);
				uni.setStorageSync(constantUtil.expirTime, res.data.data.expirTime);
				// success(res.data)
			} else {
				// fail(res.data)
			}
		},
		fail: function(res) {
			consoleUtil.log(res);
			if (message != '') {
				uni.hideLoading();
			}
			// fail(res)
		}
	});
}
//交互前先判断token是否过期
function postValidate(url, params, userId, message, success, fail) {
	let that = this;
	let loadMessage = '';
	if (url == constantUtil.getWordStudyContent || url == constantUtil.getWordDetail) {
		loadMessage = '';
		// console.log("检测接口")
	} else {
		// console.log("非检测")
		loadMessage = constantUtil.loadingTitle;
	}
	//判断token是否过期
	if (
		uni.getStorageSync(constantUtil.token) &&
		uni.getStorageSync(constantUtil.expirTime) &&
		stringUtils.changeTimestamp(uni.getStorageSync(constantUtil.expirTime).slice(0, 19)) > stringUtils
		.getTimestamp()
	) {
		consoleUtil.log('token可用');
		// consoleUtil.log("结束时间：" + stringUtils.changeTimestamp(wx.getStorageSync(constantUtil.expirTime)))
		// consoleUtil.log("当前时间" + stringUtils.getTimestamp())
		that.postRequestLG2(url, params, userId, uni.getStorageSync(constantUtil.token), loadMessage, success, fail);
	} else {
		consoleUtil.log('重新获取token');

		//new Promise模板
		new Promise((resolve, reject) => {
			consoleUtil.log('第一步获取token');
			let tokenUrl = constantUtil.getAccessToken;
			let tokenParams = {
				customId: constantUtil.customId,
				userId: userId,
				timestamp: stringUtils.getTimestamp(),
				appKey: constantUtil.appKey,
				appId: constantUtil.appId,
				sign: sha256.hex_sha256(constantUtil.customId + '\n' + constantUtil.appKey + '\n' +
					constantUtil.appId + '\n' + constantUtil.secretKey + '\n' + userId)
			};
			// consoleUtil.log(url)
			// consoleUtil.log(tokenParams)
			const postRequestTask = uni.request({
				url: tokenUrl,
				data: tokenParams,
				method: 'POST',
				success: function(res) {
					if (message != '') {
						uni.hideLoading();
					}
					if (res.statusCode == 200) {
						consoleUtil.log(res.data);
						uni.setStorageSync(constantUtil.tokenData, res.data.data);
						uni.setStorageSync(constantUtil.token, res.data.data.token);
						uni.setStorageSync(constantUtil.expirTime, res.data.data.expirTime);
						// success(res.data)

						resolve(that.postRequestLG2(url, params, userId, res.data.data.token,
							loadMessage, success, fail));
					} else {
						uni.showToast({
							title: res.data.data.message,
							icon: 'none',
							duration: 2000
						});
						// fail(res.data)
					}
				},

				fail: function(res) {
					consoleUtil.log(res);
					uni.showToast({
						title: res.data.data.message,
						icon: 'none',
						duration: 2000
					});
					// if (message != "") {
					//     wx.hideLoading()
					// }
					// fail(res)
				}
			});
		});
	}
}
//需要校验的接口
function postRequestLG2(url, params, userId, token, message, success, fail) {
	let that = this;
	if (message != '') {
		uni.showLoading({
			mask: true
			// title: message,
		});
	}

	consoleUtil.log(url);
	consoleUtil.log(params);
	const postRequestTask = uni.request({
		url: url,
		data: params,
		header: {
			userId: userId,
			token: token,
			customId: constantUtil.customId
		},
		method: 'POST',
		success: function(res) {
			if (message != '') {
				uni.hideLoading();
			}
			if (res.statusCode == 200) {
				consoleUtil.log(res.data);
				success(res.data);
			} else {
				if (res.statusCode == 401) {
					//token问题
					uni.removeStorageSync(constantUtil.token);
					that.postValidate(url, params, userId, message, success, fail);
				} else {
					fail(res.data);
				}
			}
		},
		fail: function(res) {
			consoleUtil.log(res);
			if (message != '') {
				uni.hideLoading();
			}
			fail(res);
		}
	});
}

//需要校验的接口
function uploadFile(url, params, arrayBuffer, message, success, fail) {
	let that = this;
	if (message != '') {
		uni.showLoading({
			mask: true
			// title: message,
		});
	}

	consoleUtil.log(url);
	consoleUtil.log(params);
	const postRequestTask = uni.request({
		url: url,
		data: {
			"text": JSON.stringify(params),
			"audio": arrayBuffer,
		},

		//之前用的

		header: {
			'content-type': 'multipart/form-data',
			// 'content-type': 'application/x-www-form-urlencoded',
			"Request-Index": 0,
		},
		method: 'POST',
		success: function(res) {
			if (message != '') {
				uni.hideLoading();
			}
			if (res.statusCode == 200) {
				consoleUtil.log(res.data);
				success(res.data);
			} else {
				if (res.statusCode == 401) {
					//token问题
					uni.removeStorageSync(constantUtil.token);
					that.postValidate(url, params, userId, message, success, fail);
				} else {
					fail(res.data);
				}
			}
		},
		fail: function(res) {
			consoleUtil.log(res);
			if (message != '') {
				uni.hideLoading();
			}
			fail(res);
		}
	});
}


function postRequestJson(url, params, message, success, fail) {
	if (message != '') {
		uni.showLoading({
			mask: true
			// title: message,
		});
	}
	// JSON.parse(params)
	consoleUtil.log(url);
	consoleUtil.log(params);
	const postRequestTask = uni.request({
		url: url,
		data: params,
		//   header: {
		//       'content-type': 'application/x-www-form-urlencoded'
		//     },
		header: {
			'content-type': 'application/json'
		},
		method: 'POST',
		success: function(res) {
			if (message != '') {
				uni.hideLoading();
			}
			if (res.statusCode == 200) {
				consoleUtil.log(res.data);
				success(res.data);
			} else {
				fail(res);
			}
		},
		fail: function(res) {
			consoleUtil.log(res);
			if (message != '') {
				uni.hideLoading();
			}
			fail(res);
		}
	});
}

//get请求
function getRequest(url, params, success, fail) {
	this.getRequestLoading(url, params, '', success, fail);
}

function getRequestLoading(url, params, message, success, fail) {
	if (message != '') {
		uni.showLoading({
			mask: true,
			title: message
		});
	}
	const getRequestTask = uni.request({
		url: url,
		data: params,
		// header: {
		//   'Content-Type': 'application/json'
		// },
		method: 'GET',
		success: function(res) {
			if (message != '') {
				uni.hideLoading();
			}
			if (res.statusCode == 200) {
				consoleUtil.log(res.data);
				success(res.data);
			} else {
				fail(res);
			}
		},
		fail: function(res) {
			if (message != '') {
				uni.hideLoading();
			}
			fail(res);
		}
	});
}

//取消post请求
function abortPostRequest(url, params, success, fail) {
	postRequestTask.abort();
}

//取消get请求
function abortGetRequest(url, params, success, fail) {
	getRequestTask.abort();
}
module.exports = {
	postRequest: postRequest,
	postRequestLoading: postRequestLoading,
	postRequestLG: postRequestLG,
	postRequestLG2: postRequestLG2,
	getRequest: getRequest,
	getRequestLoading: getRequestLoading,
	abortPostRequest: abortPostRequest,
	abortGetRequest: abortGetRequest,
	postRequestJson: postRequestJson,
	getToken: getToken,
	postValidate: postValidate,
	postRequestLoading2: postRequestLoading2,
	uploadFile: uploadFile,
};